#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;

void Usage(std::string proc)
{
    cout << "Usage: " << proc << " serverip serverport\n" << endl;
}

int main(int argc, char* argv[])
{   
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);


    while(true)
    {
        int cnt = 5;
        bool isReconnect = false;

        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0)
        { 
            cerr << "socket error" << endl;
            return 1;
        }
 
        // 与 udp 一样，tcp客户也不需要用户显式的绑定端口号，由系统随机端口bind (客户端发起 connect 时)
        // 没有主机会主动连接客户端，因此客户端不需要 listen，但是它需要连接服务端  

        // 写入失败或者连接失败时进行重连，重连cnt次
        do{
            int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
            if(n < 0)
            {
                isReconnect = true;
                --cnt;
                cerr << "connect error! reconnect... " << cnt << endl;
                sleep(2);
            }
            else break;
        } while (cnt && isReconnect);

        if(!cnt)
        {
            cerr << "user offline...." << endl;
            break;
        } 


        // IO操作
        // while (true)
        // {
            string message;
            cout << "Please Enter@ ";
            getline(cin, message);
            int n = write(sockfd, message.c_str(), message.size());
            if(n < 0)
            {
                cerr << "write error" << endl;
                continue;
                //break;      // 写入失败后跳出重连(while版本)
            }

            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if(n > 0)
            {
                inbuffer[n] = 0;
                cout << inbuffer << endl;
            }
        // }
        
        close(sockfd);
    }

    return 0;
}